<template>
    <div class="search-list">	
        <el-table
            :data="tableData"
            style="width: 100%;"
            :header-cell-style="cellStyle"
            :cell-style="cellStyle"
            :row-class-name="getRowClassName"
            :default-sort = "{prop: 'brand_sort' , order: 'ascending'}"
            ref="table"
            @expand-change="expandChange"
            @sort-change="sortChange"
            :header-cell-class-name="hdCellClassName" 
            :row-style="selectedstyle"
            :height="oHeight"
        >
            <el-table-column type="expand" #default="{row}" width="60" label="车款">
                <el-table
                    :data="row.details"
                    style="width: 100%"
                    :header-cell-style="cellStyle"
                    :cell-style="cellStyle"
                >
                    <el-table-column label="序号" type="index" width="70"></el-table-column>
                    <el-table-column label="车款名" min-width="180" prop="type_name">
                        <!-- <el-input v-model="row.type_name" class="power_brand_name cursorPoint"></el-input> -->
                    </el-table-column>
                    <el-table-column label="发动机参数" prop="engine">
                        <!-- <el-input v-model="row.engine" class="power_brand_name cursorPoint"></el-input> -->
                    </el-table-column>
                    <el-table-column label="厂商指导价" prop="guide_price">
                        <!-- <el-input v-model="row.guide_price" class="power_brand_name cursorPoint"></el-input> -->
                    </el-table-column>
                    <el-table-column label="是否在售" width="218" #default="{row}">
                        <el-switch
                            v-model="row.sale_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="1"
                            inactive-value="2"
							@change="updateBrandList(row, 'brandSub')"
                        ></el-switch>
                    </el-table-column>
                    <el-table-column label="操作" #default="{row}" width="140">
                        <router-link
                            class="opt"
                            :to="{name:'ytcarsParaConfig', params:{type_id: row.type_id, brand_id: $route.params.brand_id}}"
                        >参数编辑</router-link>
                        |
                        <router-link
                            class="opt"
                            :to="{name:'ytcarsBrandImage', params:{carTypeId: row.type_id, brand_id: $route.params.brand_id}}"
                        >车款图片</router-link>
                        <!--router-link
                            class="opt"
                            :to="{name:'ytcarsBrandVideo', params:{carTypeId: row.type_id, brand_id: $route.params.brand_id}}"
                        >车款视频</router-link-->
                    </el-table-column>
                </el-table>
            </el-table-column>
            <el-table-column label="排序" width="100" sortable prop="brand_sort" #default="{row}">
                <el-input v-model="row.brand_sort" class="input_box_sort cursorPoint" @blur="updateBrandList(row, 'brand', 'sort')" @change="handleChange(row)"></el-input>
            </el-table-column>
            <el-table-column label="所属车型" prop="brand_name">
                <!-- <el-input v-model="row.brand_name" class="power_brand_name cursorPoint"></el-input> -->
            </el-table-column>
            <el-table-column label="车型图" #default="{row}">
                <el-image class="brand_icon" :src="row.brand_icon" fit="cover" lazy>
                    <div slot="error" class="image-slot">
                       <i class="el-icon-picture-outline"></i>
                    </div>
                </el-image>
            </el-table-column>
            <el-table-column label="是否展示" width="190" #default="{row}">
                <el-switch
                    v-model="row.brand_show"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-value="1"
                    inactive-value="0"
					@change="updateBrandList(row, 'brand')"
                ></el-switch>
            </el-table-column>
            <el-table-column label="操作" #default="{row}" width="220">
                <el-button type="text" @click="showUploadBox(row)">车型图片</el-button> | 
                <router-link class="opt" :to="{name:'ytcarsBrandVideo', params:{carTypeId: row.brand_id, brand_id: $route.params.brand_id}}">车型视频</router-link> | 
                <el-button type="text" @click="handleUpdateCar(row.brand_id)">更新车款</el-button> |
                  <el-button type="text" title="短链点击小程序着陆渠道名: car_series_sms_track" @click="copyLink(row.brand_id,row.brand_father)">复制链接</el-button>
            </el-table-column>
        </el-table>
        <!-- 上传组件 -->
        <el-dialog
            title="车型图维护"
            :visible.sync="imageFormVisible"
            :before-close="handleClose"
            width="700px"
        >       
            <el-divider></el-divider>
            <el-form
                :model="formData"
                :rules="rules"
                ref="imageUpload"
                label-width="100px"
                label-position="right"
                size="small"
                style="width: 100%"
            >
                <el-form-item label="车型名称" prop="carName">
                    <el-input
                        style="width:300px;"
                        type="text"
                        disabled
                        v-model="rowItem.brand_name"
                    ></el-input>
                </el-form-item>

                <el-form-item label="图片上传" class="image-box" prop="imageUrlList">
                    <el-upload
                        action="#"
                        list-type="picture-card"
                        accept=".jpg,.png"
                        :show-file-list="false"
                        :http-request="handleUploadImg"
                        :file-list="imageList"
                        :before-upload="checkFile"
                        :on-exceed="handleExceed"
                        :on-change="selectFile"
                        :on-remove="removeFile"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
  						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div class="el-upload__tip">图片像素：1280*720 (16:9)，图片大小不超过2M，格式为PNG或JPG</div>
                </el-form-item>
                <!-- 进度条 -->
                <!-- <el-form-item>
                    <div class="el-progress-grid">
                        <el-progress
                            class="el-progressbar"
                            type="line"
                            v-if="progressFlag"
                            color="#67c23a"
                            :percentage="progressPercent"
                        ></el-progress>
                    </div>
                </el-form-item>-->
                <el-form-item position="right">
                    <el-button type="primary" @click="submitForm('imageUpload')" class="btnSave">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { resize } from "@/common/js/height.js";
import { brandModel } from '../api';
import ImageUpload from "./image-upload.vue";
import upload from "./upload";
export default {
    data() {
        return {
            tableData: [],
            imageFormVisible: false,
            formData: {
                imageUrlList: ""
            },
            rules: {
                imageUrlList: [
                    { required: true, message: "请上传图片", trigger: "change" },
                ],
            },
            rowItem: '',
            imageList: [], //图片文件列表
            imageClass: [], //图片分类
            limit: 1, //上传图片数量限制
			imageUrl:'',
			currImg: {},//正在上传的图片信息
            brand_id: this.$route.params.brand_id,
            currStyleBrandIds: [],
            oHeight: 600,
            sortBy: "ascending"
        }
    },
    components: { ImageUpload },
    beforeRouteEnter(to, from, next) {
        if(from.name == 'ytcarsBrandModel') {
            localStorage.setItem('styleOffsetTop', 0);
            localStorage.setItem('currStyleBrandIds', []);
            // to.meta.refresh = true;
        } else {
            // to.meta.refresh = false;
        }
         //继续执行
        next(vm => {
            /*
            if(to.meta.refresh) {
                vm.tableData = []
            }*/
        });
    },
    created() {
        this.$parent.tabLists = [
            { label: "厂商品牌", name: "ytcarsBrandModel" },
            { label: "车型车款", name: "ytcarsBrandStyle" }
        ]
        this.getTableData();
        // this.$router.push({ name: 'ytcarsBrandModel', params: { userId: '123' }})
		// console.log('======>',this)
    },
    /* 当启用keepAlive
    activated() {
        this.$parent.tabLists = [
            { label: "厂商品牌", name: "ytcarsBrandModel"},
            { label: "车型车款", name: "ytcarsBrandStyle"}
        ]
        if(this.$route.meta.refresh) {
            this.getTableData();
        }
        this.$nextTick(() => {
            // 表格内滚动条
            // this.$refs.table.bodyWrapper.scrollTop = this.$refs.table.bodyWrapper.scrollHeight
            
            // 框架布局右侧 el-main
            // document.querySelector(".el-main").scrollTop = this.$refs.table.bodyWrapper.scrollHeight

            // 初始化滚动位置
            document.querySelector(".is-scrolling-none").scrollTop = localStorage.getItem('styleOffsetTop') || 0;

            // 重新监听滚动
            // document.querySelector(".el-main").addEventListener('scroll', this.handleScroll)
 	    })
    },*/
    beforeRouteLeave(to, from, next) {
        // 离开组件则记录scrollTop值
        localStorage.setItem('styleOffsetTop', document.querySelector(".is-scrolling-none").scrollTop);
        next();
    },
    methods: {
        expandChange(row, expandedRows) {
            if(expandedRows.indexOf(row) >= 0) { // 展开
                this.currStyleBrandIds.push(row.brand_id); // 添加
                row.background = true;
            } else {
                this.currStyleBrandIds.splice(this.currStyleBrandIds.indexOf(row.brand_id), 1); // 移除
                row.background = false;
            }
            localStorage.setItem("currStyleBrandIds", this.currStyleBrandIds); // 记录当前展开的 Row
        },
        selectedstyle ({row, rowIndex}) {
		    if (row.background) {
			    return { "background-color": "#F5F7FA" };
		    }
	    },
        async getTableData() {
            const res = await this.$http.post('/admin/yt_car/index.php?act=yt_car&op=getBrandSubList', {
                brand_id: this.$route.params.brand_id
            })
            if (res.code == 1) {
                let currStyleBrandIds = localStorage.getItem("currStyleBrandIds").split(",") || [];
                let _row = [];
                if(!res.data) return;
                this.tableData = res.data.map(item => {
                    // 排序必须转为数字，不然会错乱
                    item.brand_sort = parseInt(item.brand_sort)
                    if(currStyleBrandIds.indexOf(item.brand_id) >= 0) {
                        _row.push(item)
                    }
                    return item;
                });
                this.$nextTick(() => {
                    // 展开
                    for(let row of _row) {
                        // 展开之前记录的所有行 toggleRowExpansion 第二个参数为 true 则会触发 expand-change 和 row-style 绑定的方法(row-style 会执行三次(elementui Bug))
                        this.$refs.table.toggleRowExpansion(row, true); 
                    }
                    setTimeout(() => {
                        let scrollTop = localStorage.getItem('styleOffsetTop') || 0;

                        // 不滑动
                        //document.querySelector(".is-scrolling-none").scrollTop = scrollTop;
                        //document.querySelector(".is-scrolling-none").scrollTo(0, scrollTop)

                        // 采用jquery
                        //$('.is-scrolling-none').animate({scrollTop},1000);

                        // 滑动滚动
                        this.scrollTo(document.querySelector(".is-scrolling-none"), 0, scrollTop)

                    }, 500)
                })
                // console.log(this.tableData)
            }
        },
        scrollTo(el, y, scrollTop, speed = 1) {
            setTimeout(() => {
                el.scrollTo(0, y)
                if(y >= scrollTop) return;
                if(y < scrollTop) {
                    y = y + speed;
                }
                y = y > scrollTop ? scrollTop : y;
                if(y % 10 == 0) {
                    speed += 2;
                }
                this.scrollTo(el, y, scrollTop, speed);
            }, 1)
        },
        cellStyle() {
            return { "text-align": "center" };
        },
        getRowClassName({ row, rowIndex }) {
            if (!(row.details && row.details.length > 0)) {
                return "row-expand-cover";
            }
        },
        uploadVideo(brand_id) {
            //console.log(brand_id)
            this.$router.push({ name: 'ytcarsBrandVideo', params: { "carTypeId": brand_id } })
        },
        showUploadBox(row) {
            // console.log(row)
            this.rowItem = row;
            this.imageList = row.brand_icon_old && [{imageUrl: row.brand_icon_old}] || [];
            //this.imageList = [];
            this.imageUrl = row.brand_icon
            this.imageFormVisible = true;
        },
        handleClose() {
			if(this.currImg&&!this.currImg.isUpload){
				//未完成上传则需要删除oss图片
				brandModel.deleteVideo({
					image_list:[this.currImg.filename]
				})
			}
            this.imageFormVisible = false;

			//清空弹窗信息及当前上传图片信息
			this.currImg = {};
			this.imageUrl = '';
			this.imageList = [];
			this.rowItem = '';
            this.formData.imageUrlList = ''
            this.resetForm("imageUpload");
        },
        async handleUploadImg(file) {
            let rep = await upload(
                `/admin/yt_car/index.php?act=yt_car&op=uploadSeriesImage&brand_id=${this.rowItem.brand_id}`,
                file
            );
            if (rep.code === 200) {
				this.currImg = rep.data;

                // 删除旧图片
                await this.$http.post(
                    `/admin/yt_car/index.php?act=yt_car&op=deleteImage`,
                    {
                        id: this.formData.carTypeId,
                        image_list: this.imageUrl,
                    }
                );

				this.imageUrl = URL.createObjectURL(file.file);
                this.imageList = [{imageUrl: rep.data.filename}];

                /*
                this.imageList.map((image) => {
                    if (image.uid == file.file.uid) {
                        image.imageUrl = rep.data.filename;
                    }
                });
                */
            }
        },
        //上传前检查文件
        checkFile(file) {
            const isJPG = file.type === "image/jpeg";
            const isPng = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG && !isPng) {
                this.$message.error("上传图片只能是 JPG、PNG 格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                return false;
            }
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 ${this.limit} 个文件，还可以上传 ${this.limit - fileList.length
                } 个文件`
            );
        },
        //选择图片的回调
        selectFile(file, fileList) {
            this.imageList = fileList;
        },
        //删除图片的回调
        async removeFile(file, fileList) {
            this.imageList = fileList;
            //console.log(this.imageList);
            let res = await this.$http.post(
                `/admin/yt_car/index.php?act=yt_car&op=deleteImage`,
                {
                    id: this.formData.carTypeId,
                    image_list: [file.imageUrl],
                }
            );
            //console.log(res);
            if (res.code == 1) {
                this.$message({
                    type: "success",
                    message: "删除成功!",
                });
            }
        },
        submitForm(formName) {
            if(this.imageList.length > 0) {
                this.formData.imageUrlList = this.imageList.map((image) => {
                    return image.imageUrl;
                });
            }
            // console.log(this.formData);
            let data = {
                carTypeId: this.rowItem.brand_id,
                imageUrlList: this.imageList && this.imageList[0] && this.imageList[0].imageUrl
            }
            //console.log(data,this.imageList)
            //提交配置数据
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    brandModel.saveSeriesImageUrl(data)
                        .then((res) => {
                            // console.log(res);
                            if (res.code == 1) {
								this.currImg.isUpload = true;
                                this.rowItem.brand_icon = res.image_url;
                                this.imageUrlList = null;
                                this.resetForm("imageUpload");
                                this.handleClose()
                                this.$message({
                                    type: "success",
                                    message: "保存成功!",
                                });
                            }
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        handleChange(row) {
            row.isChange = true;
        },
        hdCellClassName() {
            return 'hdCellStyle'
        },
        sortChange(obj) {
            this.sortBy = obj.order
        },
        // 更新车型、车款
		async updateBrandList(row, type = "brand", act = null) {
			let datas = {
				brand_id: row.brand_id,
				type, //类型(brand为厂商、品牌、车型更新, brandSub为车款更新)
            }
            switch(type) {
                case "brand":
                    if(act == "sort") {
                        if(!row.isChange) return;
                        datas.brand_sort = row.brand_sort;
                    } else {
                        datas.brand_show = row.brand_show;
                    }
                break;
                case "brandSub":
                    datas = {
                        ...datas, 
                        brand_id: row.type_id,
                        sale_state: row.sale_state,
                        brand_sort: row.brand_sort
                    }
                break;
            }
            const res = await this.$http.post('/admin/yt_car/index.php?act=yt_car&op=updateBrandList', datas)
			if(res.code===1){
				this.$message.success(res.msg)
                if(act == "sort") {
                    // 手动排序
                    this.$refs.table.sort('brand_sort', this.sortBy)
                    row.isChange = false
                }
			}else{
				this.$message.error(res.msg)
			}
        },
        async handleUpdateCar(brand_id) {
            try {
                // 先获取token
                const {code, msg, data} = await this.$http.post('/admin/auth/index.php?act=outerAuth&op=getJavaAuth', { brand_id })
                console.log(brand_id, 'brand_id')
                if (code == 1) {
                    let url = '/http/cluebus/col/ytcarType/colFullType' // 本地开发环境
                    if (process.env.NODE_ENV==='production') {
                        url =  window.location.origin.includes('mycjj') 
                            ? 'https://cluebus.mycjj.com:6061/col/ytcarType/colFullType'  // 正式生产环境
                            : 'https://cluebustest.chejj.cn:6061/col/ytcarType/colFullType'  // 测试生产环境
                    }
                    const {flag, msg} = await this.$http.post(url, { brandId: [parseInt(brand_id)], java_token: data.token })
                    if (flag) {
                        return this.$message.success(`${msg}`)
                    }
                    throw msg
                }
                throw msg
            } catch (error) {
                this.$message.error(`${error}`)
            }
            
        },
        copyLink(id,brand_id){
            let datas={
                id:id,//车系id	
                brand_id:brand_id//厂商id	
            }
            this.$http.get('/admin/yt_car/index.php?act=yt_car&op=getShortUrl', {params: datas}).then(res => {
            if (res.code == 1) {
                    var cText = res.data.url;
                        var aux = document.createElement("input");
                        aux.setAttribute("value", cText);
                        document.body.appendChild(aux);
                        aux.select();
                        document.execCommand("copy");
                        document.body.removeChild(aux);
                        alert("链接复制成功!");
            }else {
                alert(res.msg);
            }
        })
      
        },
    },
	mounted() {
        /**
         * 在未固定图片高度时，则无法准确计算高度，即使在$nextTick中执行也是一样, 解决方法：
         * 1、固定图片高度
         * 2、使用watch 监听tableData变化，当变化时候再使用$nextTick(()=>{resize(this)})
         */
		resize(this)
	}
}
</script>
<style scoped lang="scss">
.search-list {
    margin-top: 20px;
    // height: calc(100% - 70px);
    // overflow: auto;
    >.el-table{
        border: 1px solid #EBEEF5;
        border-bottom: 0;
    }
}
.input_box_sort /deep/input {
    width: 80px;
    text-align: center;
}
.power_brand_name /deep/input {
    width: 130px;
    text-align: center;
}
.brand_icon {
    max-width: 80px;
    height: 45px;
    background: #F5F7FA;
    display: flex;
    margin: 0 auto;
    align-items: center;
    justify-content: space-around;
}
.opt {
    color: #3b8ee4;
    margin: 0 2px 0;
}
/deep/.row-expand-cover .el-table__expand-icon {
    visibility: hidden;
}
/deep/.showbk{
    background: #555;
}
/deep/.el-upload--picture-card {
    height:84px;
    line-height: 92px;
}
.avatar{
    width: 100%;
    height: 100%;
}

/deep/.el-table__expanded-cell{
    padding: 16px 15px 18px!important;
    .el-table{
        border: 1px solid #EBEEF5;
        border-bottom: 0;
        .el-table__header th{
            font-weight:bold!important;
        }
    }
}
/deep/.hdCellStyle {
    padding: 3px 0;
}
/deep/.el-table__body-wrapper{
    overflow: auto;
}
</style>